package com.soujiayi.activity;

import java.util.Calendar;
import java.util.HashMap;

import com.soujiayi.net.HttpRequester;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.Constants;
import com.soujiayi.util.UserKeeper;
import com.soujiayi.weibo.User;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Selection;
import android.text.Spannable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class EditProfileActivity extends Activity {

	private User user;
	private EditText et_edit_name;
	private TextView tv_edit_gender;
	private TextView tv_edit_birthday;
	private TextView tv_edit_city;
	private Handler handler;
	private HttpRequester httpRequester;
	private ProgressDialog progressDialog;
	private String cityId = "";
	private String cityName = "";
	private int mYear;
	private int mMonth;
	private int mDay;
	private String date;
	private DatabaseManager databaseManager = new DatabaseManager(
			EditProfileActivity.this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.edit_profile);
		initViews();

	}

	public void initViews() {
		et_edit_name = (EditText) findViewById(R.id.et_edit_name);
		tv_edit_gender = (TextView) findViewById(R.id.tv_edit_gender);
		tv_edit_city = (TextView) findViewById(R.id.tv_edit_city);
		tv_edit_birthday = (TextView) findViewById(R.id.tv_edit_birthday);

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);

				if (msg.what == 'c') {
					cityName = msg.getData().getString("title");
					tv_edit_city.setText(cityName);
					cityId = msg.getData().getString("id");
				} else if (msg.what == 'p') {
					progressDialog.dismiss();
					if (msg.arg1 == 1) {
						databaseManager
								.updateUserFields(
										user.getUid(),
										null,
										et_edit_name.getText().toString(),
										tv_edit_gender
												.getText()
												.equals(EditProfileActivity.this
														.getString(R.string.male)) ? "1"
												: "0", cityId, cityName,tv_edit_birthday.getText().toString());
						UserKeeper
								.updateUser(
										EditProfileActivity.this,
										Constants.PREFERENCES_NAME_USER,
										null,
										et_edit_name.getText().toString(),
										tv_edit_gender
												.getText()
												.equals(EditProfileActivity.this
														.getString(R.string.male)) ? "1"
												: "0", cityId, cityName,
												tv_edit_birthday.getText().toString());
						Toast.makeText(
								EditProfileActivity.this,
								EditProfileActivity.this
										.getString(R.string.profile_update_success),
								Toast.LENGTH_SHORT).show();
					} else if (msg.arg1 == 0) {
						Toast.makeText(
								EditProfileActivity.this,
								EditProfileActivity.this
										.getString(R.string.profile_update_fail),
								Toast.LENGTH_SHORT).show();
					} else if (msg.arg1 == -1) {
						Toast.makeText(
								EditProfileActivity.this,
								EditProfileActivity.this
										.getString(R.string.profile_update_netexception),
								Toast.LENGTH_SHORT).show();
					}
				}
			}
		};

		httpRequester = new HttpRequester(this,1, handler);

		user = UserKeeper.readUser(EditProfileActivity.this,
				Constants.PREFERENCES_NAME_USER);
		if (user != null) {
			if (user.getNickname() != null && !"".equals(user.getNickname())) {
				et_edit_name.setText(user.getNickname());
				CharSequence text = et_edit_name.getText();
				if (text instanceof Spannable) {
					Spannable spanText = (Spannable) text;
					Selection.setSelection(spanText, text.length());
				}
			}

			if (user.getGender() != null && !user.getGender().equals("")) {
				if (user.getGender().equals("1")) {
					tv_edit_gender.setText(this.getResources().getString(
							R.string.male));
				} else {
					tv_edit_gender.setText(this.getResources().getString(
							R.string.female));
				}
			}
			
			if (user.getBirthday() != null && !user.getBirthday().equals("")) {
					tv_edit_birthday.setText(user.getBirthday());
			}

			if (user.getCityName() != null && !user.getCityName().equals("")) {
				tv_edit_city.setText(user.getCityName());
				// httpRequester.getMemberCity(((MyApplication)this.getApplication()).getSessionId(),
				// user.getCityId());
			}
		}

		tv_edit_gender.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				final String[] gender = new String[] {
						EditProfileActivity.this.getString(R.string.female),
						EditProfileActivity.this.getString(R.string.male) };
				new AlertDialog.Builder(EditProfileActivity.this)
						.setTitle(
								EditProfileActivity.this
										.getString(R.string.edit_select_gender))
						.setItems(gender,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int i) {
										tv_edit_gender.setText(gender[i]);
									}
								}).show();
			}

		});
		tv_edit_city.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(EditProfileActivity.this,
						CityListActivity.class);
				EditProfileActivity.this.startActivityForResult(intent, 1);
			}

		});

		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		tv_edit_birthday.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new DatePickerDialog(EditProfileActivity.this,
						new DatePickerDialog.OnDateSetListener() {
							public void onDateSet(DatePicker view, int year,
									int monthOfYear, int dayOfMonth) {
								mYear = year;
								mMonth = monthOfYear;
								mDay = dayOfMonth;

								if((mMonth+1)<10)
									if(mDay<10)
										date = mYear+"0"+(int)(mMonth+1)+"0"+mDay;
									else
										date = mYear+"0"+(int)(mMonth+1)+""+mDay;
								else
									if(mDay<10)
										date = mYear+""+(int)(mMonth+1)+"0"+mDay;
									else
										date = mYear+""+(int)(mMonth+1)+""+mDay;
								
								tv_edit_birthday.setText(date);
							};
						}, mYear, mMonth, mDay).show();

			}

		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode != Activity.RESULT_OK)
			return;
		if (requestCode == 1) {
			cityId = data.getExtras().getString("id");
			cityName = data.getExtras().getString("title");
			tv_edit_city.setText(cityName);
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	public void save(View view) {
		HashMap<String, String> parameters = new HashMap<String, String>();
		parameters.put("sid",
				((MyApplication) this.getApplication()).getSessionId());
		parameters.put("nickname", et_edit_name.getText().toString());
		parameters
				.put("sex",
						tv_edit_gender.getText().equals(
								this.getString(R.string.male)) ? "1" : "0");
		parameters.put("cityid", cityId);
		parameters.put("birthday", tv_edit_birthday.getText().toString());
		progressDialog = new ProgressDialog(EditProfileActivity.this);
		progressDialog.setMessage(getResources().getString(
				R.string.profile_updating));
		progressDialog.setCancelable(false);
		progressDialog.show();
		httpRequester.updateProfile(parameters);
	}

	public void back(View view) {
		EditProfileActivity.this.setResult(Activity.RESULT_OK, null);
		this.finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		this.finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}
}
